package com.example.onlinereadingsystem.demos.web.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.onlinereadingsystem.demos.web.dto.domain.User;
import com.example.onlinereadingsystem.demos.web.dto.request.LoginParam;
import com.example.onlinereadingsystem.demos.web.dto.request.RegisterParam;
import com.example.onlinereadingsystem.demos.web.dto.vo.LoginVo;
import com.example.onlinereadingsystem.demos.web.service.LoginService;
import com.example.onlinereadingsystem.demos.web.service.UserService;
import com.example.onlinereadingsystem.demos.web.util.JwtTokenUtil;
import com.example.onlinereadingsystem.demos.web.util.RedisUtil;
import com.example.onlinereadingsystem.demos.web.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 登录逻辑实现
 * @Author ljm
 * @Date 2024/10/9
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserService userService;
    @Value("${spring.secret}")
    private String secret;

    @Autowired
    private RedisUtil redisUtil;

    private final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";

    /**
     * @auther ljm
     * @create 2024/12/30
     * @describe 登录接口
     */
    @Override
    public Result<LoginVo> login(LoginParam param) {
        String code = param.getCode().toLowerCase();
        if (Strings.isEmpty(code)) {
            return Result.error("验证码不能为空");
        }
        String key = param.getKey();
        String origin = code + key + secret;
        String realyKey = SecureUtil.md5(origin);
        log.info("realyKey:{},code:{}", realyKey, code);
        Object checkCode = redisUtil.get(realyKey);
        if (checkCode == null || !checkCode.toString().equals(code)) {
            return Result.error("验证码错误");
        } else {
            redisUtil.del(realyKey);
        }
        User user;
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, param.getUsername())
                .eq(User::getPassword, param.getPassword());
        user = userService.getOne(queryWrapper);
        if (user != null) {
            // shiro登录认证
//            UsernamePasswordToken token = new UsernamePasswordToken(param.getUsername(),param.getPassword());
//            Subject subject = SecurityUtils.getSubject();
//            subject.login(token);

            Map<String, Object> map = new HashMap<>();
            map.put("userName", user.getUsername());
            map.put("userId", user.getId());
            String jwtToken = JwtTokenUtil.createToken(map);
            // 设置session过期时间 永不过期
//            subject.getSession().setTimeout(-1001);
            LoginVo loginVo = new LoginVo();
            loginVo.setToken(jwtToken);
            loginVo.setUserId(user.getId());
            return Result.OK(loginVo);
        }
        return Result.error("用户名或密码错误！");
    }

    /**
     * @auther ljm
     * @create 2024/12/30
     * @describe 注册接口
     */
    @Override
    public Result<Boolean> register(RegisterParam param) {
        if (Strings.isEmpty(param.getUsername()) || Strings.isEmpty(param.getPassword())) {
            return Result.error("用户名或密码不能为空");
        }
        if (userService.getBaseMapper().selectCount(new LambdaQueryWrapper<User>().eq(User::getUsername, param.getUsername())) > 0) {
            return Result.error("用户名已存在");
        }
        User user = new User();
        BeanUtils.copyProperties(param, user);
        userService.save(user);
        return Result.OK(true);
    }

    /**
     * @auther ljm
     * @create 2024/12/30
     * @describe 生成验证码图片
     */
    @Override
    public Result<String> randomImage(String key) {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 50);
        String res = lineCaptcha.getImageBase64Data();
        String code = lineCaptcha.getCode().toLowerCase();
        String origin = code + key + secret;
        String realyKey = SecureUtil.md5(origin);
        //输出code
        log.info("realyKey:{},key:{},code:{}", realyKey, key, lineCaptcha.getCode());
        redisUtil.set(realyKey, code, 60);
        return Result.OK(res);
    }
}
